﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Truextend.Training.Model.Entities;
using Truextend.Training.Presenter.ViewInterfaces;
using Truextend.Training.Business;
using Truextend.Training.Business.Utility;
using Truextend.Training.Service;

namespace Truextend.Training.Presenter
{
    public class CourseInstanceDetailPresenter
    {
        private PageMode pageMode;
        private CourseInstance courseInstanceRecovery = null;
        private long courseInstanceId;
        private long courseId;
        private ICourseInstanceDetailView view;
        private Course course;
        
        public CourseInstanceDetailPresenter(string cId, string cvId, ICourseInstanceDetailView view)
        {
            this.view = view;

            if( !long.TryParse(cvId, out courseInstanceId) )
            {
                courseInstanceId = 0;
            }

            if (!long.TryParse(cId, out courseId))
            {
                courseId = 0;
            }

            if(cvId == null && courseInstanceId == 0 )
            {
                pageMode = PageMode.New;
            }
            else
            {
                pageMode = PageMode.Edition;
                                 
            }

            // load data for course if is new
            if (pageMode == PageMode.New && courseId != 0 )
            {
                long courseIdLong = Convert.ToInt32(courseId);
                //course = CourseControl.GetCourseById(courseIdLong);
                course = new CourseService().GetCourseById(courseIdLong);
                view.Course = course;
                
            }
        }

        
        public void LoadCourseInstanceDataInView()
        {            
            // load data for edit
            long courseInstanceIdLong = Convert.ToInt32(courseInstanceId);
            courseInstanceRecovery = new CourseInstanceService().GetCourseInstanceById(courseInstanceIdLong);

            view.Location = courseInstanceRecovery.Location;
            view.InstructorId = courseInstanceRecovery.InstructorId;
            DateTime startTime = courseInstanceRecovery.ScheduleCourses.First().StartTime;
            DateTime endTime = courseInstanceRecovery.ScheduleCourses.First().EndTime;
            DateTime startDate = courseInstanceRecovery.StartDate;
            DateTime endDate = courseInstanceRecovery.EndDate;

            view.StartDate = new DateTime(startDate.Year, startDate.Month, startDate.Day, startTime.Hour, startTime.Minute, startTime.Second);
            view.EndDate = new DateTime(endDate.Year, endDate.Month, endDate.Day, endTime.Hour, endTime.Minute, endTime.Second);

            List<string> days = new List<string>();
            foreach (ScheduleCourse sc in courseInstanceRecovery.ScheduleCourses)
            {
                days.Add(sc.StartTime.ToString("dddd"));
            }
            view.DaysWeek = days;

            course = new CourseService().GetCourseById(courseInstanceRecovery.Course.CourseId);
            view.Course = course;
        }

        public void InitControls()
        {
            view.PageModeInTitle = pageMode;
            view.LoadDaysWeek();

            // load other data for droplist, grid, etc
        }
        
        public PageMode PageMode
        {
            get { return pageMode; }
        }


        public void OnSave(Course cView)
        {
            CourseInstance courseInstanceToBeSaved = null;

            if (cView == null)
            {
                view.RedirectToCourseInstanceManageList();
            }

            course = cView;
            
            try
            {
                courseInstanceToBeSaved = FillCourseInstance(new CourseInstance());
                List<ScheduleCourse> scheduleCourseList = GetScheduleCourseList(courseInstanceToBeSaved);
                
                System.Data.Objects.DataClasses.EntityCollection<ScheduleCourse> list = new System.Data.Objects.DataClasses.EntityCollection<ScheduleCourse>();
                foreach(ScheduleCourse item in scheduleCourseList)
                {
                    list.Add(item);
                }
                courseInstanceToBeSaved.ScheduleCourses = list;
                //courseInstanceToBeSaved =  CourseInstanceControl.AddCourseInstance(courseInstanceToBeSaved);
                courseInstanceToBeSaved = new CourseInstanceService().AddCourseInstance(courseInstanceToBeSaved);
                
                if (courseInstanceToBeSaved.CourseInstanceId > 0)
                {
                    view.RedirectToCourseInstanceManageList();
                }
                else
                {
                    // error
                }

            }

            catch (Exception)
            {
            }
            
        }

        public static Course GetCourse(string id)
        {
            long courseIdLong = Convert.ToInt32(id);
            //return CourseControl.GetCourseById(courseIdLong);
            return new CourseService().GetCourseById(courseIdLong);
        }

        public static CourseInstance GetCourseInstance(string id)
        {
            long courseInstanceIdLong = Convert.ToInt32(id);
            //return CourseControl.GetCourseById(courseIdLong);
            return new CourseInstanceService().GetCourseInstanceById(courseInstanceIdLong);
        }

        private CourseInstance FillCourseInstance(CourseInstance courseInstance)
        {
            if (pageMode == PageMode.New)
            {
                courseInstance.CourseReference.EntityKey = course.EntityKey;
            }
            courseInstance.Location = view.Location;
            courseInstance.InstructorId = view.InstructorId;
            courseInstance.StartDate = view.StartDate;
            courseInstance.EndDate = view.EndDate;
            courseInstance.State = "AP";

                        
            /*
            courseVersion.StartTime = view.StartTime;
            courseVersion.EndTime = view.EndTime;
            courseVersion.Days = view.GetDays();
             */

            return courseInstance;
        }

        private List<ScheduleCourse> GetScheduleCourseList(CourseInstance courseInstance)
        {
            List<ScheduleCourse> scheduleCourseList = GeneratorScheduleCourse.GetScheduleCourse(courseInstance.StartDate, courseInstance.EndDate,
                                                            view.StartDate, view.EndDate, view.DaysWeek);
            return scheduleCourseList;
        }

        public void OnUpdate(string instanceId)
        {
            
            CourseInstance courseInstanceToBeSaved = null;
            if (instanceId == null)
            {
                view.RedirectToCourseInstanceManageList();
            }
            else
            {
                long courseInstanceIdLong = Convert.ToInt32(instanceId);
                courseInstanceToBeSaved = new CourseInstance();
                courseInstanceToBeSaved.CourseInstanceId = courseInstanceIdLong;
            }

            try
            {
                courseInstanceToBeSaved = FillCourseInstance(courseInstanceToBeSaved);
                // Delete ScheduleCourses
                //courseInstanceToBeSaved.ScheduleCourses.Clear();
                // Add new ScheduleCourses
                List<ScheduleCourse> scheduleCourseList = GetScheduleCourseList(courseInstanceToBeSaved);

                System.Data.Objects.DataClasses.EntityCollection<ScheduleCourse> list = new System.Data.Objects.DataClasses.EntityCollection<ScheduleCourse>();
                foreach (ScheduleCourse item in scheduleCourseList)
                {
                    list.Add(item);
                    //courseInstanceToBeSaved.ScheduleCourses.Add(item);
                }
                courseInstanceToBeSaved.ScheduleCourses = list;
                
                courseInstanceToBeSaved = new CourseInstanceService().EditCourseInstance(courseInstanceToBeSaved);

                if (courseInstanceToBeSaved.CourseInstanceId > 0)
                {
                    view.RedirectToCourseInstanceManageList();
                }
                else
                {
                    // error
                }

            }

            catch (Exception)
            {
            }
            
        }

        public bool InformationIsValid()
        {
            bool isValid = true;

            // Location Error
            if (view.Location.Trim().Equals(string.Empty))
            {
                view.SetError("Location is a required field", ViewPanelError.Location);
                isValid = false;
            }

            // Instructor Error
            if (view.InstructorId == 0)
            {
                view.SetError("Instructor is a required field", ViewPanelError.Instructor);
                isValid = false;
            }

            DateTime startDate = view.StartDate;
            DateTime endDate = view.EndDate;
            
            // Dates Errors
            if (startDate.Date == endDate.Date)
            {
                view.SetError("From and end range dates are required fields", ViewPanelError.Dates);
                isValid = false;
            }
            else
            {
                if (startDate.Date > endDate.Date)
                {
                    view.SetError("End date must be greater than the start date", ViewPanelError.Dates);
                    isValid = false;
                }
            }

            // Times Errors
            DateTime startTime = new DateTime(1, 1, 1, startDate.Hour, startDate.Minute, startDate.Second);
            DateTime endTime = new DateTime(1, 1, 1, endDate.Hour, endDate.Minute, endDate.Second);

            if (startTime == endTime)
            {
                view.SetError("From and end range times are required fields", ViewPanelError.Dates);
                isValid = false;
            }
            else
            {
                if (startTime > endTime)
                {
                    view.SetError("End time must be greater than the start time", ViewPanelError.Dates);
                    isValid = false;
                }
            }            

            //
            if (view.DaysWeek == null)
            {
                view.SetError("Select at least one day", ViewPanelError.Recurrence);
                isValid = false;
            }
            else
            {
                if (view.DaysWeek.Count < 1)
                {
                    view.SetError("Select at least one day", ViewPanelError.Recurrence);
                    isValid = false;
                }
            }

            return isValid;
        }
    }

    /// <summary>
    /// Enum to indicate if a course version details page is in new, edit or read only mode.
    /// </summary>
    public enum PageMode
    {
        New, Edition, ReadOnly
    }

    public enum ViewPanelError
    {
        Location, Dates, Times, Recurrence, Instructor
    }
}
